package org.example.blogserver.dao.impl;

import org.example.blogserver.dao.SysUserDao;
import org.example.blogserver.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class SysUserDaoImpl implements SysUserDao {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public SysUserDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int insertUser(SysUser user) {
        String sql = "INSERT INTO ms_sys_user (account, role, avatar, nickname, password) VALUES (?, ?, ?, ?, ?)";
        return jdbcTemplate.update(sql, user.getAccount(), user.getRole(), user.getAvatar(), user.getNickname(), user.getPassword());
    }

    @Override
    public int deleteUserByAccount(String account) {
        String sql = "DELETE FROM ms_sys_user WHERE account = ?";
        return jdbcTemplate.update(sql, account);
    }

    @Override
    public SysUser findUserByAccount(String account) {
        String sql = "SELECT * FROM ms_sys_user WHERE account = ?";
        List<SysUser> users = jdbcTemplate.query(sql, new Object[]{account}, (rs, rowNum) -> {
            SysUser user = new SysUser();
            user.setAccount(rs.getString("account"));
            user.setRole(rs.getString("role"));
            user.setAvatar(rs.getBytes("avatar"));
            user.setNickname(rs.getString("nickname"));
            user.setPassword(rs.getString("password"));
            return user;
        });

        // 检查结果列表是否为空
        if (!users.isEmpty()) {
            System.out.println(users.get(0));
            // 返回第一个用户
            return users.get(0);
        } else {
            System.out.println("用户不存在");
            // 如果没有找到用户，可以返回 null 或者抛出自定义异常
            return null;
        }
    }


    @Override
    public int updateNicknameByAccount(String account, String newNickname) {
        String sql = "UPDATE ms_sys_user SET nickname = ? WHERE account = ?";
        return jdbcTemplate.update(sql, newNickname, account);
    }

    @Override
    public int updateAvatarByAccount(String account, byte[] newAvatar) {
        String sql = "UPDATE ms_sys_user SET avatar = ? WHERE account = ?";
        return jdbcTemplate.update(sql, newAvatar, account);
    }

    @Override
    public int updatePasswordByAccount(String account, String newPassword) {
        String sql = "UPDATE ms_sys_user SET password = ? WHERE account = ?";
        return jdbcTemplate.update(sql, newPassword, account);
    }

    @Override
    public List<SysUser> getUserList() {
        String sql = "SELECT * FROM ms_sys_user";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SysUser.class));
    }
}
